var PwdKey = "vss.230331150607"

func addSuffix(key string) []byte {
	keyBytes := []byte(key)
	switch l := len(keyBytes); {
	case l < 16:
		keyBytes = append(keyBytes, make([]byte, 16-l)...)
	case l > 16:
		keyBytes = keyBytes[:16]
	}
	return keyBytes
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func encryptECB(key string, origData []byte) ([]byte, error) {
	keyBytes := addSuffix(key)
	cipher, err := aes.NewCipher(keyBytes)
	if err != nil {
		return nil, err
	}
	length := (len(origData) + aes.BlockSize) / aes.BlockSize
	plain := make([]byte, length*aes.BlockSize)
	copy(plain, origData)
	pad := byte(len(plain) - len(origData))
	for i := len(origData); i < len(plain); i++ {
		plain[i] = pad
	}
	var encrypted = make([]byte, len(plain))
	// 分组分块加密
	for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Encrypt(encrypted[bs:be], plain[bs:be])
	}
	return encrypted, nil
}

func decryptECB(key string, encrypted []byte) ([]byte, error) {
	cipher, err := aes.NewCipher(addSuffix(key))
	if err != nil {
		return nil, err
	}
	var decrypted = make([]byte, len(encrypted))
	//
	for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}
	if trim < 0 || trim > len(decrypted) {
		return nil, nil
	}
	return decrypted[:trim], nil
}

func EncryptBy(key string, val string) string {
	origData := []byte(val)
	crypted, err := encryptECB(key, origData)
	if err != nil {
		return ""
	}
	return hex.EncodeToString(crypted)
}

func DecryptBy(key string, val string) string {
	crypted, err := hex.DecodeString(val)
	if err != nil {
		return ""
	}
	origData, err := decryptECB(key, crypted)
	if err != nil {
		return ""
	}
	return string(origData)
}